package com.live.dengdengtv.activity.live;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.live.dengdengtv.BaseActivity;
import com.live.dengdengtv.R;
import com.live.dengdengtv.activity.support.CurLiveInfo;
import com.live.dengdengtv.activity.support.GiftShowManager;
import com.live.dengdengtv.activity.support.InputTextMsgDialog;
import com.live.dengdengtv.activity.support.LiveGroupMsgAdapter;
import com.live.dengdengtv.activity.support.LiveMemberListHelper;
import com.live.dengdengtv.adapter.CustomArrayAdapter;
import com.live.dengdengtv.adapter.LinkMicDialogAdpter;
import com.live.dengdengtv.bean.AppInfo;
import com.live.dengdengtv.bean.LoginInfo;
import com.live.dengdengtv.bean.SimpleInfoData;
import com.live.dengdengtv.bean.gson.CustomMsg;
import com.live.dengdengtv.bean.gson.GUserInfo;
import com.live.dengdengtv.fragment.ChatFragment;
import com.live.dengdengtv.fragment.ConversationItemClick;
import com.live.dengdengtv.fragment.FragmentStopLis;
import com.live.dengdengtv.fragment.GiftFragment;
import com.live.dengdengtv.fragment.MsgFragment;
import com.live.dengdengtv.kernel.avcontrollers.QavsdkControl;
import com.live.dengdengtv.kernel.model.ChatEntity;
import com.live.dengdengtv.kernel.model.LiveInfoJson;
import com.live.dengdengtv.kernel.presenters.viewinface.EnterQuiteRoomView;
import com.live.dengdengtv.kernel.presenters.viewinface.LiveView;
import com.live.dengdengtv.bean.Constants;
import com.live.dengdengtv.kernel.utils.LogConstants;
import com.live.dengdengtv.kernel.utils.SxbLog;
import com.live.dengdengtv.kernel.views.customviews.HeartLayout;
import com.live.dengdengtv.net.NetTaskList;
import com.live.dengdengtv.net.callback.AbstractRequestBack;
import com.live.dengdengtv.utils.AppDialog;
import com.live.dengdengtv.utils.DateUtils;
import com.live.dengdengtv.view.CircleImageView;
import com.live.dengdengtv.view.HorizontalListView;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.tencent.TIMFriendResult;
import com.tencent.TIMFriendshipManager;
import com.tencent.TIMMessage;
import com.tencent.TIMValueCallBack;
import com.tencent.av.TIMAvManager;
import com.tencent.av.sdk.AVView;
import com.umeng.socialize.ShareAction;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.media.UMImage;

import java.io.File;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import pl.droidsonroids.gif.GifImageView;

public class LiveingActivity extends BaseActivity implements EnterQuiteRoomView,View.OnClickListener{
    private final String TAG = "EnterLiveHelper3";

    private final int TASK_FOLLOW_MEMBER = 1;
    private final int TASK_GET_REDPACKET = 2;
    private final int TASK_GET_HOST_INFO = 3;
    private final int TASK_ADD_BLACKLIST = 4;

    private static final int ACTIVITY_CODE_REDPACKET = 110;

    private Activity context = this;
    private EnterLiveHelper mEnterRoomHelper;
    private LiveHelper mLiveHelper;

    private String backGroundId;
    private View avView;
    private LinearLayout mHostLeaveLayout;

    private ArrayList<String> mRenderUserList = new ArrayList<String>();


    private LiveViewImp liveViewImp;
    private ListView mListViewMsgItems;
    private ArrayList<ChatEntity> mArrayListChatEntity;
//    private ChatMsgListAdapter mChatMsgListAdapter;
    private LiveGroupMsgAdapter mChatMsgListAdapter;

    private static final int UPDAT_WALL_TIME_TIMER_TASK = 1;
    private static final int TIMEOUT_INVITE = 2;
    private static final int CLOSE_REDPACKET = 10;

    private Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            switch (msg.what) {
                case UPDAT_WALL_TIME_TIMER_TASK:
//                    updateWallTime();
                    break;
                case REFRESH_LISTVIEW:
                    doRefreshListView();
                    break;
                case TIMEOUT_INVITE:
                    String id = "" + msg.obj;
                    cancelInviteViewed(id);
                    mLiveHelper.sendGroupMessage(Constants.AVIMCMD_MULTI_HOST_CANCELINVITE, id);
                    break;
                case CLOSE_REDPACKET:
                    redpacket_tv.setVisibility(View.GONE);
                    break;
            }
            return false;
        }
    });

    private HorizontalListView member_list_hlv;
    /**当前时间日历*/
    private Calendar startCalendar;
    private TextView count_tv;
    private FrameLayout fragment_container_fl;
//    private FrameLayout fragment_container;

    private CircleImageView host_head_iv;

    //房间成员
    private List<CustomMsg.CustomUserInfo> memberList = new ArrayList<CustomMsg.CustomUserInfo>();
    private CustomArrayAdapter memberAdpter;

    private TextView invite_view1;
    /**送礼动画管理*/
    private GiftShowManager giftShowManager;
    /**虚拟券*/
    private TextView virTicket_tv;
    /**红包*/
    private TextView redpacket_tv;

    private boolean isFullScreen = false;

    //全屏控制布局
    private RelativeLayout host_head_rl;
    private LinearLayout virTicket_ll;
    private TextView room_id;
    private TextView current_time_tv;
    private LinearLayout liveing_member_bottom;
    private LinearLayout liveing_host_bottom;
    private View shut_fullscreen_tv;
    private View liveing_message_input_tv;
    private View btn_back;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        requestWindowFeature(Window.FEATURE_NO_TITLE);//去掉标题栏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON, WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);   // 不锁屏
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);//去掉信息栏
//        setContentView(R.layout.activity_live);
        setContentView(R.layout.activity_liveing);
        checkPermission();
        //进出房间的协助类
        mEnterRoomHelper = new EnterLiveHelper(this, this);
        //房间内的交互协助类
        liveViewImp = new LiveViewImp();
        mLiveHelper = new LiveHelper(this, liveViewImp);

        initView();
        registerReceiver();
        backGroundId = CurLiveInfo.getHostID();

        //进入房间流程
        mEnterRoomHelper.startEnterRoom();
        //设置如果当前获得的preview数据和之前的preview数据来自不同的摄像头时触发此回调
        mLiveHelper.setCameraPreviewChangeCallback();

        initGiftShowManager();


    }

    private void initGiftShowManager(){
        List<View> layoutGift = new ArrayList<View>();
        LinearLayout gift_container_ll = (LinearLayout) findViewById(R.id.gift_container_ll);
        for(int i=0;i< gift_container_ll.getChildCount();i++ ){
            layoutGift.add(gift_container_ll.getChildAt(i));
        }

        GifImageView gifImageView = (GifImageView) findViewById(R.id.gifImageView);

        giftShowManager = new GiftShowManager(LiveingActivity.this,layoutGift,gifImageView,virTicket_tv);
        giftShowManager.startGift();
    }

    private void initView() {
        startCalendar = Calendar.getInstance();
        avView = findViewById(R.id.av_video_layer_ui);//surfaceView;
        //离开时显示布局
        mHostLeaveLayout = (LinearLayout)findViewById(R.id.ll_host_leave);

        fragment_container_fl = (FrameLayout)findViewById(R.id.fragment_container_fl);
        fragment_container_fl.setOnClickListener(this);
//        fragment_container = (FrameLayout)findViewById(R.id.fragment_container);

        //房间成员人数
//        LinearLayout count_ll = (LinearLayout)findViewById(R.id.count_ll);
        count_tv = (TextView)findViewById(R.id.head_text_tv);

        //主播头像布局
        host_head_rl = (RelativeLayout)findViewById(R.id.host_head_rl);
        host_head_iv = (CircleImageView)findViewById(R.id.head_iv);
        setUrlImage(host_head_iv);
        host_head_iv.setOnClickListener(this);
        TextView name_tv = (TextView) findViewById(R.id.name_tv);
        String name = CurLiveInfo.getHostName();
        name_tv.setText(TextUtils.isEmpty(name) ? CurLiveInfo.getHostID():name);
        ImageView sex_iv = (ImageView) findViewById(R.id.sex_iv);
        String mSex = AppInfo.loginInfo.getUserSex();
//        if("1".equals(mSex)){
//            sex_iv.setImageResource();
//        }else if("2".equals(mSex)){
//            sex_iv.setImageResource();
//        }
        ImageView start_iv = (ImageView) findViewById(R.id.start_iv);

        /*房间号*/
        room_id = (TextView) findViewById(R.id.room_id);
        room_id.setText("ID："+CurLiveInfo.getChatRoomId());
        //当前时间
        current_time_tv = (TextView) findViewById(R.id.current_time_tv);
        current_time_tv.setText(DateUtils.dateToString(startCalendar.getTime(),DateUtils.yyyy_M_d));

        //虚拟券
        virTicket_ll = (LinearLayout) findViewById(R.id.virTicket_ll);
        virTicket_tv = (TextView) findViewById(R.id.virTicket_tv);


        //红包
        redpacket_tv = (TextView) findViewById(R.id.redpacket_tv);

        //聊天信息
        mListViewMsgItems = (ListView) findViewById(R.id.im_msg_listview);
        mArrayListChatEntity = new ArrayList<ChatEntity>();
//        mChatMsgListAdapter = new ChatMsgListAdapter(this, mListViewMsgItems, mArrayListChatEntity);
//        mListViewMsgItems.setAdapter(mChatMsgListAdapter);
        mChatMsgListAdapter = new LiveGroupMsgAdapter(this, mListViewMsgItems, mArrayListChatEntity);
        mListViewMsgItems.setAdapter(mChatMsgListAdapter);
        //房间成员,最多显示10名
        member_list_hlv = (HorizontalListView)findViewById(R.id.member_list_hlv);
        memberAdpter = new CustomArrayAdapter(context, memberList);
        member_list_hlv.setAdapter(memberAdpter);
//        addMembers();


        //观看者 底部布局
        liveing_member_bottom = (LinearLayout)findViewById(R.id.liveing_member_bottom);
        //主播 底部布局
        liveing_host_bottom = (LinearLayout)findViewById(R.id.liveing_host_bottom);


        //布局控制
        if (CurLiveInfo.getIdStatus() == Constants.HOST) {//主播 为当前用户
            liveing_member_bottom.setVisibility(View.GONE);
            liveing_host_bottom.setVisibility(View.VISIBLE);
//            count_ll.setVisibility(View.VISIBLE);
//            host_head_rl.setVisibility(View.GONE);

            initBackDialog();
            initDetailDailog();

            virTicket_tv.setText(LoginInfo.getInstance().getVirTicket()+"");
        }else {
            getHostInfo();

            liveing_member_bottom.setVisibility(View.VISIBLE);
            liveing_host_bottom.setVisibility(View.GONE);
//            count_ll.setVisibility(View.GONE);
//            host_head_rl.setVisibility(View.VISIBLE);
            invitedDialog();
        }

        invite_view1 = (TextView) findViewById(R.id.invite_view1);

;
        findViewById(R.id.controll_ui).setOnClickListener(this);
        btn_back = findViewById(R.id.btn_back);
        btn_back.setOnClickListener(this);
        liveing_message_input_tv = findViewById(R.id.liveing_message_input_tv);
        liveing_message_input_tv.setOnClickListener(this);

        liveing_member_bottom.findViewById(R.id.liveing_share_tv).setOnClickListener(this);
//        liveing_host_bottom.findViewById(R.id.liveing_share_tv).setOnClickListener(this);
        liveing_member_bottom.findViewById(R.id.liveing_message_tv).setOnClickListener(this);
        liveing_member_bottom.findViewById(R.id.liveing_add_tv).setOnClickListener(this);
        liveing_member_bottom.findViewById(R.id.liveing_gift_tv).setOnClickListener(this);

        liveing_host_bottom.findViewById(R.id.liveing_message_tv).setOnClickListener(this);
        liveing_host_bottom.findViewById(R.id.liveing_redpacket_tv).setOnClickListener(this);
        liveing_host_bottom.findViewById(R.id.liveing_leftarr_tv).setOnClickListener(this);
        liveing_host_bottom.findViewById(R.id.liveing_add_tv).setOnClickListener(this);

        shut_fullscreen_tv = findViewById(R.id.shut_fullscreen_tv);
        shut_fullscreen_tv.setOnClickListener(this);
    }

    private void setUrlImage(ImageView imageView) {

            String avatarAddress = CurLiveInfo.getAvatorurl();
            if(!TextUtils.isEmpty(avatarAddress)){
                if(avatarAddress.startsWith("http")){
                    ImageLoader.getInstance().displayImage(avatarAddress, imageView);
                }else {
                    imageView.setImageURI(Uri.fromFile(new File(avatarAddress)));
                }
            }
    }

    private void startRecord(){
        TIMAvManager.RecordParam mRecordParam = TIMAvManager.getInstance().new RecordParam();
        mRecordParam.setFilename(CurLiveInfo.getHostID()+System.currentTimeMillis());
        mRecordParam.setClassId(26869);//关注26952
        mRecordParam.setTransCode(false);//转码
        mRecordParam.setSreenShot(false);//截图
        mRecordParam.setWaterMark(false);//水印
//        mRecordParam.addTag("");//标签

        Log.e(TAG,"开始录屏...");
        mLiveHelper.startRecord(mRecordParam);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.controll_ui:
                HeartLayout heart_layout = (HeartLayout) findViewById(R.id.heart_layout);
                heart_layout.addFavor();
                break;
            case R.id.btn_back:
                quiteLiveByPurpose();break;
            case R.id.head_iv:
                showHostDetail();break;
            case R.id.liveing_share_tv:
                showShareDialog();
                break;
            case R.id.liveing_message_input_tv:
                showInputMsgDialog();
                break;
            case R.id.liveing_message_tv:
                showMsgDetail();break;
            case R.id.liveing_gift_tv:
                showGiftDialog();break;
            case R.id.liveing_redpacket_tv:
                goRedpacketActivity();
                break;
            case R.id.liveing_leftarr_tv:
                showLiveControl(v);
                break;
            case R.id.liveing_add_tv:
//                if(CurLiveInfo.getIdStatus() == Constants.HOST){
//                    showLinkMicDialog();
//                }else {
//                    showLinkMicrophone(v);
//                }
                switchFullScreen((TextView) v);
                break;
            case R.id.shut_fullscreen_tv:
                switchFullScreen((TextView) v);
                break;
            case R.id.fragment_container_fl:
                getSupportFragmentManager().popBackStackImmediate();
//                fragment_container_fl.setVisibility(View.GONE);
                break;
        }
    }

    private void switchFullScreen(TextView tv){

        if(isFullScreen){
            host_head_rl.setVisibility(View.VISIBLE);
            virTicket_ll.setVisibility(View.VISIBLE);
            room_id.setVisibility(View.VISIBLE);
            current_time_tv.setVisibility(View.VISIBLE);
            if (CurLiveInfo.getIdStatus() == Constants.HOST) {
                liveing_host_bottom.setVisibility(View.VISIBLE);
            }else {
                liveing_member_bottom.setVisibility(View.VISIBLE);
            }
            btn_back.setVisibility(View.VISIBLE);
            mListViewMsgItems.setVisibility(View.VISIBLE);
            liveing_message_input_tv.setVisibility(View.VISIBLE);
            shut_fullscreen_tv.setVisibility(View.GONE);
            member_list_hlv.setVisibility(View.VISIBLE);
//            tv.setBackgroundResource(R.mipmap.screen_nomal);
        }else {
            host_head_rl.setVisibility(View.INVISIBLE);
            virTicket_ll.setVisibility(View.INVISIBLE);
            room_id.setVisibility(View.INVISIBLE);
            current_time_tv.setVisibility(View.INVISIBLE);
            liveing_member_bottom.setVisibility(View.INVISIBLE);
            liveing_host_bottom.setVisibility(View.INVISIBLE);
            btn_back.setVisibility(View.INVISIBLE);
            mListViewMsgItems.setVisibility(View.INVISIBLE);
            liveing_message_input_tv.setVisibility(View.INVISIBLE);
            shut_fullscreen_tv.setVisibility(View.VISIBLE);
            member_list_hlv.setVisibility(View.GONE);
//            tv.setBackgroundResource(R.mipmap.screen_full);
        }
        isFullScreen = !isFullScreen;
    }

    private void goRedpacketActivity(){
        int memberNum = memberList.size();
//        if(memberNum <=0 ){
//            Notice.alert(context,"房间成员为0!");
//            return;
//        }
        Intent intent = new Intent(this, RedpacketActivity.class);
        intent.putExtra(RedpacketActivity.Extra_MEMBERNUM, memberNum+"");
        startActivityForResult(intent, ACTIVITY_CODE_REDPACKET);
    }

    private void getHostInfo(){
        HashMap<String,String> headInfo = new HashMap<String,String>();
        headInfo.put("token",AppInfo.TOKEN);
        headInfo.put("phone_type",AppInfo.PHONE_TYPE);
        headInfo.put("phone_system_version",AppInfo.getPhone_app_version());
        headInfo.put("phone_app_version",AppInfo.getPhone_app_version());
        headInfo.put("client_id",AppInfo.getClient_id());
        headInfo.put("user_id",CurLiveInfo.getHostID());
        requestData(NetTaskList.get_userInfo,headInfo, TASK_GET_HOST_INFO);
    }
    //网络数据返回
    @Override
    public boolean onResponse(SimpleInfoData response, int id) {
        if (response.result == 0) {

            if(id == TASK_FOLLOW_MEMBER){
                Toast.makeText(context,"关注成功",Toast.LENGTH_SHORT).show();
            }else if(id == TASK_GET_REDPACKET){
                try {
                    String virtualCoin = response.data.getAsJsonObject().get("count_of_virtual_coin").getAsString();
                    redpacket_tv.setText(virtualCoin+"\n虚拟币");
                    LoginInfo.getInstance().addVirCoin(virtualCoin);//刷新用户虚拟币
                    //关闭红包界面
                    Message msg = new Message();
                    msg.what = CLOSE_REDPACKET;
                    mHandler.sendMessageDelayed(msg, 3 * 1000);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if(id == TASK_GET_HOST_INFO){
                GUserInfo userInfo = new Gson().fromJson(response.data.getAsJsonObject(), GUserInfo.class);
                try {
                    CurLiveInfo.setVirTicket(Integer.parseInt(userInfo.virtual_ticket));
                    virTicket_tv.setText(CurLiveInfo.getVirTicket()+"");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }else if(id == TASK_ADD_BLACKLIST){
                Toast.makeText(context, "加入黑名单成功!", Toast.LENGTH_SHORT).show();
            }

        }
        return false;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode == ACTIVITY_CODE_REDPACKET){
            if(resultCode == Activity.RESULT_OK){

                final String redPacketId = data.getStringExtra(RedpacketActivity.Extra_redpacketId);
                mLiveHelper.sendGroupMessage(Constants.AVIMCMD_send_redpacket, redPacketId,
                        new TIMValueCallBack<TIMMessage>() {
                            @Override
                            public void onError(int i, String s) {
                                Toast.makeText(context,"网络错误..",Toast.LENGTH_SHORT).show();
                            }
                            @Override
                            public void onSuccess(TIMMessage timMessage) {
//                                showRedPacket(redPacketId);
                            }
                        });
                Toast.makeText(context,"正在发送..",Toast.LENGTH_SHORT).show();
            }
        }
    }

    public void showRedPacket(final String redPacketId){
        redpacket_tv.setVisibility(View.VISIBLE);
        redpacket_tv.setText("立即\n抢红包");
        redpacket_tv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                HashMap<String,String> params = new HashMap<String, String>();
                params.put("red_packet_id",redPacketId);//红包id
                params.putAll(AppInfo.getHeadInfo());
                requestData(NetTaskList.get_redpacket, params,TASK_GET_REDPACKET);
            }
        });

        Message msg = new Message();
        msg.what = CLOSE_REDPACKET;
        mHandler.sendMessageDelayed(msg, 8 * 1000);
    }

    private void showLinkMicrophone(View v) {
//        AppDialog.showAlertDialog(this, "确认向主播发出连麦申请吗?", "确定");
        AppDialog.showAlertDialog(this, "您的等级不够，无法申请连麦！", "确定");
    }

    private void showLiveControl(View view) {
        View content = View.inflate(context,R.layout.liveing_host_ctrl,null);

        // 创建PopupWindow对象
        final PopupWindow pop = new PopupWindow(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT);
        // 需要设置一下此参数，点击外边可消失
        pop.setContentView(content);
        pop.setBackgroundDrawable(new BitmapDrawable());
        // 设置点击窗口外边窗口消失
        pop.setOutsideTouchable(true);
        // 设置此参数获得焦点，否则无法点击
        pop.setFocusable(true);
        pop.setTouchable(true);

        int w = View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED);
        int h = w;
        content.measure(w, h);
        pop.showAsDropDown(view,-content.getMeasuredWidth(),-view.getMeasuredHeight());

        content.findViewById(R.id.liveing_share_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showShareDialog();
                pop.dismiss();
            }
        });
        content.findViewById(R.id.crtl_flash_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mLiveHelper.isFrontCamera() == true) {
                    //TODO 提示
                    Toast.makeText(context, "前置摄像头无闪光灯..", Toast.LENGTH_SHORT).show();
                } else {
                    mLiveHelper.toggleFlashLight();
                }
                pop.dismiss();
            }
        });
        content.findViewById(R.id.crtl_turn_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLiveHelper.switchCamera();
                pop.dismiss();
            }
        });
        content.findViewById(R.id.crtl_beauty_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showBeautyDialog();
                pop.dismiss();
            }
        });
    }
//=================================================美颜===================================================================
    private int mBeautyRate, mWhiteRate;
    private SeekBar.OnSeekBarChangeListener beautySettingListener = new SeekBar.OnSeekBarChangeListener() {
        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            if (seekBar.getId() == R.id.beauty_progress) {
                Toast.makeText(context, "美颜度 " + mBeautyRate + "%", Toast.LENGTH_SHORT).show();//美颜度
            } else {
                Toast.makeText(context, "美白度 " + mWhiteRate + "%", Toast.LENGTH_SHORT).show();//美白度
            }
        }
        @Override
        public void onStartTrackingTouch(SeekBar seekBar) { }
        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,  boolean fromUser) {
            if (seekBar.getId() == R.id.beauty_progress) {
                mBeautyRate = progress;
                QavsdkControl.getInstance().getAVContext().getVideoCtrl().inputBeautyParam(getBeautyProgress(progress));//美颜
            } else {
                mWhiteRate = progress;
                QavsdkControl.getInstance().getAVContext().getVideoCtrl().inputWhiteningParam(getBeautyProgress(progress));//美白
            }
        }
    };
    private float getBeautyProgress(int progress) {
        return (9.0f * progress / 100.0f);
    }
    private void showBeautyDialog() {
        final Dialog beautyDialog = getDialogInstance(R.layout.dialog_beauty);
        SeekBar beauty_progress = (SeekBar)beautyDialog.findViewById(R.id.beauty_progress);
        SeekBar white_progress = (SeekBar)beautyDialog.findViewById(R.id.white_progress);

        beauty_progress.setOnSeekBarChangeListener(beautySettingListener);
        white_progress.setOnSeekBarChangeListener(beautySettingListener);

        TextView beauty_setting_finish = (TextView)beautyDialog.findViewById(R.id.beauty_setting_finish);
        beauty_setting_finish.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                beautyDialog.dismiss();
            }
        });

        beauty_progress.setProgress(mBeautyRate);
        white_progress.setProgress(mWhiteRate);
        beautyDialog.show();
    }
//=======================================美颜=====END==============================================================

    private void showMsgDetail() {
        fragment_container_fl.setVisibility(View.VISIBLE);
        MsgFragment fragment = new MsgFragment();
        fragment.setOnItemClickListener(new ConversationItemClick() {
            @Override
            public void onConversationItemClick(String id) {
                showChatDialog(id);
            }
        });
        fragment.setOnStopLis(new FragmentStopLis() {
            @Override
            public void onFragmentStop() {
                int count = getSupportFragmentManager().getBackStackEntryCount();
                if(count == 0){
                    fragment_container_fl.setVisibility(View.GONE);
                }
            }
        });
        FragmentTransaction fragmentTransaction1 = getSupportFragmentManager().beginTransaction();
        fragmentTransaction1.setCustomAnimations(R.anim.push_up_in, R.anim.push_down_out)
                .add(R.id.fragment_container, fragment)
                .addToBackStack("MsgFragment")
                .commit();


    }
//
//    private void showChatDialog(String chatId ) {
//
//        ChatDialogFragment chatDialogFragment = new ChatDialogFragment();
//        Bundle bundle = new Bundle();
//        bundle.putString(ChatFragment.C2C_ID,chatId);
//        chatDialogFragment.setArguments(bundle);
//        chatDialogFragment.show(getSupportFragmentManager(),"chatDialog");
//    }

    private void showChatDialog(String chatId) {
        fragment_container_fl.setVisibility(View.VISIBLE);

        ChatFragment fragment = ChatFragment.newInstance(chatId, true);

        fragment.setOnStopLis(new FragmentStopLis() {
            @Override
            public void onFragmentStop() {
                int count = getSupportFragmentManager().getBackStackEntryCount();
                if(count == 0){
                    fragment_container_fl.setVisibility(View.GONE);
                }
            }
        });
        FragmentTransaction fragmentTransaction1 = getSupportFragmentManager().beginTransaction();
        fragmentTransaction1.setCustomAnimations(R.anim.push_up_in, R.anim.push_down_out)
                .add(R.id.fragment_container, fragment)
                .addToBackStack("ChatFragment")
                .commit();
    }
    private void showGiftDialog() {
        fragment_container_fl.setVisibility(View.VISIBLE);
        GiftFragment fragment = GiftFragment.newInstance(giftShowManager,giftShowManager.getGiftList(), mLiveHelper);

        fragment.setOnStopLis(new FragmentStopLis() {
            @Override
            public void onFragmentStop() {
                int count = getSupportFragmentManager().getBackStackEntryCount();
                if(count == 0){
                    fragment_container_fl.setVisibility(View.GONE);
                }
            }
        });
        FragmentTransaction fragmentTransaction1 = getSupportFragmentManager().beginTransaction();
        fragmentTransaction1.setCustomAnimations(R.anim.push_up_in, R.anim.push_down_out)
                .add(R.id.fragment_container, fragment)
                .addToBackStack("GiftFragment")
                .commit();
    }



    CustomMsg.CustomUserInfo curMemberInfo;
    private void showLinkMicDialog(){
        final Dialog linkMicDialog = getDialogInstance(R.layout.dialog_liveing_linkmic);
        linkMicDialog.show();
        ListView listView = (ListView)linkMicDialog.findViewById(R.id.listView);
        LinkMicDialogAdpter.LinkMicListener lis = new LinkMicDialogAdpter.LinkMicListener(){

            @Override
            public void onPreLinkMic(CustomMsg.CustomUserInfo memberInfo) {
                if(memberInfo.isOnVideoChat == false){
                    inviteLinkMic(memberInfo.userId);
                    linkMicDialog.dismiss();
                    memberInfo.isOnVideoChat = true;

                    curMemberInfo = memberInfo;
                }else {
                    cancelInviteViewed(memberInfo.userId);
                    cancelMemberView(memberInfo.userId);
                    linkMicDialog.dismiss();
                }
            }
        };
        LinkMicDialogAdpter adpter = new LinkMicDialogAdpter(context,memberList,lis);
        listView.setAdapter(adpter);

    }

    private int inviteViewCount = 0;
    private boolean isInviting = false;
    private void inviteLinkMic(String id){
        invite_view1.setVisibility(View.VISIBLE);

/*
        int index = QavsdkControl.getInstance().getAvailableViewIndex(1);
        if (index == -1) {
            Toast.makeText(context, "最多邀请3个人!", Toast.LENGTH_SHORT).show();
            return ;
        }
        int requetCount = index + inviteViewCount;
        if (requetCount > 3) {
            Toast.makeText(context, "最多邀请3个人!", Toast.LENGTH_SHORT).show();
            return ;
        }
*/

        if(isInviting == true){
            Toast.makeText(context, "正在邀请!", Toast.LENGTH_SHORT).show();
        }

        mLiveHelper.sendC2CMessage(Constants.AVIMCMD_MUlTI_HOST_INVITE, "", id);
        //30s超时取消
        Message msg = new Message();
        msg.what = TIMEOUT_INVITE;
        msg.obj = id;
        mHandler.sendMessageDelayed(msg, 30 * 1000);

        isInviting = true;
    }

    private  Dialog invitedDialog;
    private void invitedDialog(){
        invitedDialog = new AlertDialog.Builder(context)
                .setTitle("提示")
                .setMessage("主播邀请你互动直播")
                .setPositiveButton("同意", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //上麦 ；
                        mLiveHelper.changeAuthandRole(true, Constants.VIDEO_MEMBER_AUTH, Constants.VIDEO_MEMBER_ROLE);
                        dialog.dismiss();
                    }
                })
                .setNegativeButton("拒绝", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        mLiveHelper.sendC2CMessage(Constants.AVIMCMD_MUlTI_REFUSE, "", CurLiveInfo.getHostID());
                        dialog.dismiss();
                    }
                })
                .create();
    }
    private void memberAcceptInvite(String id){
        invite_view1.setVisibility(View.GONE);
        isInviting = true;
        curMemberInfo.isOnVideoChat = true;
    }
    private void cancelInviteViewed(String id){
        invite_view1.setVisibility(View.GONE);
        isInviting = false;
        curMemberInfo.isOnVideoChat = false;
    }

    private void cancelMemberView(String id) {

        mLiveHelper.sendGroupMessage(Constants.AVIMCMD_MULTI_CANCEL_INTERACT, id);
        QavsdkControl.getInstance().closeMemberView(id);
        isInviting = false;
    }

    private void showHostDetail() {
        final Dialog hostDetail = getDialogInstance(R.layout.dialog_host_info);
        hostDetail.show();
        CircleImageView avatar_iv = (CircleImageView)hostDetail.findViewById(R.id.avatar_iv);
        TextView name_tv = (TextView)hostDetail.findViewById(R.id.name_tv);

        TextView host_id_tv = (TextView)hostDetail.findViewById(R.id.host_id_tv);
        TextView host_sign_tv = (TextView)hostDetail.findViewById(R.id.host_sign_tv);
        ImageView sex_iv = (ImageView)hostDetail.findViewById(R.id.sex_iv);


        setUrlImage(avatar_iv);
        String name = CurLiveInfo.getHostName();
        name_tv.setText(TextUtils.isEmpty(name) ? CurLiveInfo.getHostID():name);
        host_id_tv.setText(CurLiveInfo.getHostID());


        if(CurLiveInfo.getIdStatus() == Constants.HOST){
            hostDetail.findViewById(R.id.report_tv).setVisibility(View.GONE);
            hostDetail.findViewById(R.id.blacklisted_tv).setVisibility(View.GONE);
            hostDetail.findViewById(R.id.divide_v).setVisibility(View.INVISIBLE);
            hostDetail.findViewById(R.id.action_ll).setVisibility(View.INVISIBLE);
        }
        hostDetail.findViewById(R.id.report_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(CurLiveInfo.getIdStatus() == Constants.MEMBER){
                    Toast.makeText(context,"感谢您的举报，我们会尽快处理！",Toast.LENGTH_SHORT).show();
                    hostDetail.dismiss();
                }
            }
        });
        hostDetail.findViewById(R.id.blacklisted_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(CurLiveInfo.getIdStatus() == Constants.MEMBER){
//                    Map<String, String> params = new HashMap<String, String>();
//                    params.put("black_user_id",CurLiveInfo.getHostID());
//                    params.putAll(AppInfo.getHeadInfo());
//                    requestData(NetTaskList.add_blacklist, params,TASK_ADD_BLACKLIST);
//                    hostDetail.dismiss();

                    List<String> blackList = new ArrayList<String>();
                    blackList.add(CurLiveInfo.getHostID());
                    TIMFriendshipManager.getInstance().addBlackList(blackList, new TIMValueCallBack<List<TIMFriendResult>>() {
                        @Override
                        public void onError(int i, String s) {
                            Toast.makeText(context,"网络错误！",Toast.LENGTH_SHORT).show();
                        }

                        @Override
                        public void onSuccess(List<TIMFriendResult> timFriendResults) {
                            Toast.makeText(context,"加入黑名单成功！",Toast.LENGTH_SHORT).show();
                        }
                    });
                    hostDetail.dismiss();
                }
;
            }
        });
        hostDetail.findViewById(R.id.follow_ac_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(CurLiveInfo.getIdStatus() == Constants.MEMBER){
                    Map<String, String> params = new HashMap<String, String>();
                    params.put("follower_id",LoginInfo.getInstance().getUserId());
                    params.put("be_concerned_id", CurLiveInfo.getHostID());
                    requestData(NetTaskList.follow_member, params,TASK_FOLLOW_MEMBER);
                    hostDetail.dismiss();
                }
            }
        });
        hostDetail.findViewById(R.id.private_msg_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(CurLiveInfo.getIdStatus() == Constants.MEMBER){
                    showChatDialog(CurLiveInfo.getHostID());
                    hostDetail.dismiss();
                }
            }
        });
        hostDetail.findViewById(R.id.reply_tv).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(CurLiveInfo.getIdStatus() == Constants.MEMBER){
                    String nickName = CurLiveInfo.getHostName();
                    if(TextUtils.isEmpty(nickName)){
                        nickName = CurLiveInfo.getHostID();
                    }
                    showInputMsgDialog("@"+ nickName+" ");
                    hostDetail.dismiss();
                }
            }
        });

    }

    private Dialog getDialogInstance(int layoutResID){
        Dialog dialog = new Dialog(this, R.style.dialog_info);
        dialog.setContentView(layoutResID);

        Window dialogWindow = dialog.getWindow();

        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        DisplayMetrics outMetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        lp.width = outMetrics.widthPixels; //设置宽度
        dialogWindow.setAttributes(lp);

        dialogWindow.setGravity(Gravity.BOTTOM);

        dialog.setCancelable(true);
        return dialog;
    }

    /**发消息弹出框*/
    private void showInputMsgDialog() {
        showInputMsgDialog("");
    }
    private void showInputMsgDialog(String text) {
        InputTextMsgDialog inputMsgDialog = new InputTextMsgDialog(this, R.style.inputdialog, mLiveHelper, this);
        if(!TextUtils.isEmpty(text)){
            inputMsgDialog.setMessageText(text);
        }
        WindowManager.LayoutParams lp = inputMsgDialog.getWindow().getAttributes();
        DisplayMetrics outMetrics = new DisplayMetrics();
        this.getWindowManager().getDefaultDisplay().getMetrics(outMetrics);
        lp.width = outMetrics.widthPixels; //设置宽度

        inputMsgDialog.getWindow().setAttributes(lp);
        inputMsgDialog.getWindow().setGravity(Gravity.BOTTOM);
        inputMsgDialog.setCancelable(true);
        inputMsgDialog.show();
    }

    private void showShareDialog() {
        new ShareAction(this).setDisplayList(SHARE_MEDIA.WEIXIN,SHARE_MEDIA.WEIXIN_CIRCLE,SHARE_MEDIA.QQ,SHARE_MEDIA.QZONE,SHARE_MEDIA.SINA)
                .withTitle("噔噔直播")
                .withText("伙伴们噔噔开始直播了~。~")
                .withMedia(new UMImage(this,"http://v1.qzone.cc/avatar/201401/10/21/15/52cff2758d9f8112.jpg%21200x200.jpg"))
                .withTargetUrl("http://www.dengdeng.com/")
                .setCallback(umShareListener)
                .open();
    }


    /**
     * 被动退出直播
     */
    private void quiteLivePassively() {
        Toast.makeText(this, "Host leave Live ", Toast.LENGTH_SHORT);
        mLiveHelper.perpareQuitRoom(false);
    }

    /**
     * 点击Back键
     */
    @Override
    public void onBackPressed() {
        if (!getSupportFragmentManager().popBackStackImmediate()) {
            quiteLiveByPurpose();

            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if(LiveingActivity.this != null && !LiveingActivity.this.isFinishing()){
                        LiveingActivity.this.finish();
                    }
                }
            },7000);
        }
    }
    /**
     * 主动退出直播
     */
    private void quiteLiveByPurpose() {
        if (CurLiveInfo.getIdStatus() == Constants.HOST) {
            if (backDialog.isShowing() == false)
                backDialog.show();
        } else {
            mLiveHelper.perpareQuitRoom(true);
        }
    }

    /**旁路直播*/
    private static boolean isPushed = false;

    /**===========================主播按下返回键 对话框==========================================*/
    private Dialog backDialog;
    private void initBackDialog() {
        backDialog = new Dialog(this, R.style.dialog);
        backDialog.setContentView(R.layout.dialog_end_live);
        TextView tvSure = (TextView) backDialog.findViewById(R.id.btn_sure);
        tvSure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //如果是直播，发消息
                if (null != mLiveHelper) {
                    mLiveHelper.perpareQuitRoom(true);
                    if (isPushed) {
                        mLiveHelper.stopPushAction();
                    }
                }
                backDialog.dismiss();
            }
        });
        TextView tvCancel = (TextView) backDialog.findViewById(R.id.btn_cancel);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                backDialog.cancel();
            }
        });
    }/*===========================主播按下返回键 对话框=================END======================*/

    @Override
    protected void onResume() {
        super.onResume();
        mLiveHelper.resume();
        QavsdkControl.getInstance().onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mLiveHelper.pause();
        QavsdkControl.getInstance().onPause();
    }
    @Override
    protected void onDestroy() {
//        stopOrientationListener();
//        watchCount = 0;

        giftShowManager.stop();

        super.onDestroy();

//        inviteViewCount = 0;


        CurLiveInfo.setMembers(0);
        CurLiveInfo.setAdmires(0);
        CurLiveInfo.setCurrentRequestCount(0);
        unregisterReceiver();
        mLiveHelper.onDestory();
        mEnterRoomHelper.onDestory();
        QavsdkControl.getInstance().clearVideoMembers();
        QavsdkControl.getInstance().onDestroy();
    }


    private void registerReceiver() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION_SURFACE_CREATED);
        intentFilter.addAction(Constants.ACTION_HOST_ENTER);
        intentFilter.addAction(Constants.ACTION_CAMERA_OPEN_IN_LIVE);
        intentFilter.addAction(Constants.ACTION_CAMERA_CLOSE_IN_LIVE);
        intentFilter.addAction(Constants.ACTION_SWITCH_VIDEO);
        intentFilter.addAction(Constants.ACTION_HOST_LEAVE);
        registerReceiver(mBroadcastReceiver, intentFilter);
    }
    private void unregisterReceiver() {
        unregisterReceiver(mBroadcastReceiver);
    }

    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            //AvSurfaceView 初始化成功
            if (action.equals(Constants.ACTION_SURFACE_CREATED)) {
                //打开摄像头
                if (CurLiveInfo.getIdStatus() == Constants.HOST) {
                    mLiveHelper.openCameraAndMic();
                }
            }

            if (action.equals(Constants.ACTION_CAMERA_OPEN_IN_LIVE)) {//有人打开摄像头
                ArrayList<String> ids = intent.getStringArrayListExtra("ids");
                //如果是自己本地直接渲染
                for (String id : ids) {
                    if (id.equals(backGroundId)){
                        mHostLeaveLayout.setVisibility(View.GONE);
                    }
                    if (!mRenderUserList.contains(id)) {
                        mRenderUserList.add(id);
                    }

                    if (id.equals(LoginInfo.getInstance().getUserId())) {
                        liveViewImp.showVideoView(true, id);
                        return;
//                        ids.remove(id);
                    }
                }
                //其他人一并获取
                SxbLog.d(TAG, LogConstants.ACTION_VIEWER_SHOW + LogConstants.DIV + LoginInfo.getInstance().getUserId() + LogConstants.DIV + "somebody open camera,need req data"
                        + LogConstants.DIV + LogConstants.STATUS.SUCCEED + LogConstants.DIV + "ids " + ids.toString());
                int requestCount = CurLiveInfo.getCurrentRequestCount();
                mLiveHelper.requestViewList(ids);
                requestCount = requestCount + ids.size();
                CurLiveInfo.setCurrentRequestCount(requestCount);
//                }
            }

            if (action.equals(Constants.ACTION_CAMERA_CLOSE_IN_LIVE)) {//有人关闭摄像头
                ArrayList<String> ids = intent.getStringArrayListExtra("ids");
                //如果是自己本地直接渲染
                for (String id : ids) {
                    mRenderUserList.remove(id);
                    if (id.equals(backGroundId)) {
                        mHostLeaveLayout.setVisibility(View.VISIBLE);
                        return;
                    }
                }
            }

            if (action.equals(Constants.ACTION_SWITCH_VIDEO)) {//点击成员回调
                /*backGroundId = intent.getStringExtra(Constants.EXTRA_IDENTIFIER);
                SxbLog.v(TAG, "switch video enter with id:"+ backGroundId);

                if (mRenderUserList.contains(backGroundId)){
                    mHostLeaveLayout.setVisibility(View.GONE);
                }else{
                    mHostLeaveLayout.setVisibility(View.VISIBLE);
                }

                if (MySelfInfo.getInstance().getIdStatus() == Constants.HOST) {//自己是主播
                    if (backGroundId.equals(MySelfInfo.getInstance().getId())) {//背景是自己
                        mHostCtrView.setVisibility(View.VISIBLE);
                        mVideoMemberCtrlView.setVisibility(View.INVISIBLE);
                    } else {//背景是其他成员
                        mHostCtrView.setVisibility(View.INVISIBLE);
                        mVideoMemberCtrlView.setVisibility(View.VISIBLE);
                    }
                } else {//自己成员方式
                    if (backGroundId.equals(MySelfInfo.getInstance().getId())) {//背景是自己
                        mVideoMemberCtrlView.setVisibility(View.VISIBLE);
                        mNomalMemberCtrView.setVisibility(View.INVISIBLE);
                    } else if (backGroundId.equals(CurLiveInfo.getHostID())) {//主播自己
                        mVideoMemberCtrlView.setVisibility(View.INVISIBLE);
                        mNomalMemberCtrView.setVisibility(View.VISIBLE);
                    } else {
                        mVideoMemberCtrlView.setVisibility(View.INVISIBLE);
                        mNomalMemberCtrView.setVisibility(View.INVISIBLE);
                    }

                }*/

            }
            if (action.equals(Constants.ACTION_HOST_LEAVE)) {//主播结束
                quiteLivePassively();
            }


        }
    };

    @Override
    public void enterRoomComplete(int id_status, boolean isSucc) {
        //必须得进入房间之后才能初始化UI
        mEnterRoomHelper.initAvUILayer(avView);
        //设置预览回调，修正摄像头镜像
        mLiveHelper.setCameraPreviewChangeCallback();
        if (isSucc == true) {
            //IM初始化
            mLiveHelper.initTIMListener("" + CurLiveInfo.getRoomNum());

            if (id_status == Constants.HOST) {//主播方式加入房间成功
                //开启摄像头渲染画面
                startRecord();//开始录制
                SxbLog.i(TAG, "createlive enterRoomComplete isSucc" + isSucc);
            } else {
                //发消息通知上线
                mLiveHelper.sendGroupMessage(Constants.AVIMCMD_EnterLive, "");
                //TODO 获取群成员
                new LiveMemberListHelper(memberAdpter, memberList).getMemberList();

            }
        }
    }

    private Dialog mDetailDialog;
    private TextView mDetailTime, mDetailAdmires, mDetailWatchCount;
    private void initDetailDailog() {
        mDetailDialog = new Dialog(this, R.style.dialog);
        mDetailDialog.setContentView(R.layout.dialog_live_detail);
        mDetailTime = (TextView) mDetailDialog.findViewById(R.id.tv_time);
        mDetailAdmires = (TextView) mDetailDialog.findViewById(R.id.tv_admires);
        mDetailWatchCount = (TextView) mDetailDialog.findViewById(R.id.tv_members);

        mDetailDialog.setCancelable(false);

        TextView tvCancel = (TextView) mDetailDialog.findViewById(R.id.btn_cancel);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mDetailDialog.dismiss();
                finish();
            }
        });
    }
    @Override
    public void quiteRoomComplete(int id_status, boolean succ, LiveInfoJson liveinfo) {
        if (CurLiveInfo.getIdStatus() == Constants.HOST) {
            if ((getBaseContext() != null) && (null != mDetailDialog) && (mDetailDialog.isShowing() == false)) {
                SxbLog.d(TAG, LogConstants.ACTION_HOST_QUIT_ROOM + LogConstants.DIV + LoginInfo.getInstance().getUserId() + LogConstants.DIV + "quite room callback"
                        + LogConstants.DIV + LogConstants.STATUS.SUCCEED + LogConstants.DIV + "id status " + id_status);
                mDetailTime.setText(getLiveTime());//直播时间
                mDetailAdmires.setText("" + CurLiveInfo.getAdmires());//获赞数量
                mDetailWatchCount.setText("" + CurLiveInfo.getMembers());
                mDetailDialog.show();
            }
        } else {
            finish();
        }
    }

    private String getLiveTime(){
        Calendar currCal = Calendar.getInstance();
        long stime = startCalendar.getTimeInMillis();
        long ctime = currCal.getTimeInMillis();
        long time = ctime - stime;

        long h, m, s;
        s = time/1000 % 60;
        m = time/(1000*60) % 60;
        h = time/(1000*60*60) % 60;

        String ss, ms ,hs;
        ss = s>=10 ? ""+s :"0"+s;
        ms = m>=10 ? ""+m :"0"+m;
        hs = h>=10 ? ""+h :"0"+h;

        return  hs +":"+ ms +":"+ ss;
    }


    @Override
    public void memberQuiteLive(String[] list) {
        if (list == null) return;
        for (String id : list) {
            SxbLog.i(TAG, "memberQuiteLive id " + id);
            if (CurLiveInfo.getHostID().equals(id)) {
                if (CurLiveInfo.getIdStatus() == Constants.MEMBER)
                    quiteLivePassively();
            }
        }
    }
    @Override
    public void memberJoinLive(String[] list) {

    }
    @Override
    public void alreadyInLive(String[] list) {
        for (String id : list) {
            if (id.equals(LoginInfo.getInstance().getUserId())) {
                QavsdkControl.getInstance().setSelfId(LoginInfo.getInstance().getUserId());
                QavsdkControl.getInstance().setLocalHasVideo(true, LoginInfo.getInstance().getUserId());
            } else {
                Log.e("setRemoteHasVideo","==========================alreadyInLive");
                QavsdkControl.getInstance().setRemoteHasVideo(true, id, AVView.VIDEO_SRC_TYPE_CAMERA);
            }
        }
    }


    private boolean mBoolRefreshLock = false;
    private boolean mBoolNeedRefresh = false;
    private ArrayList<ChatEntity> mTmpChatList = new ArrayList<ChatEntity>();//缓冲队列
    private final Timer mTimer = new Timer();
    private TimerTask mTimerTask = null;
    private static final int REFRESH_LISTVIEW = 5;
    private static final int MINFRESHINTERVAL = 500;
    /**
     * 消息刷新显示
     *
     * @param name    发送者
     * @param context 内容
     * @param type    类型 （上线线消息和 聊天消息）
     */
    public void refreshTextListView(String name, String context, int type) {
        ChatEntity entity = new ChatEntity();
        entity.setSenderName(name);
        entity.setContext(context);
        entity.setType(type);
        //mArrayListChatEntity.add(entity);
        notifyRefreshListView(entity);
        //mChatMsgListAdapter.notifyDataSetChanged();

        mListViewMsgItems.setVisibility(View.VISIBLE);
        SxbLog.d(TAG, "refreshTextListView height " + mListViewMsgItems.getHeight());

        if (mListViewMsgItems.getCount() > 1) {
            if (true)
                mListViewMsgItems.setSelection(0);
            else
                mListViewMsgItems.setSelection(mListViewMsgItems.getCount() - 1);
        }
    }
    public void refreshTextListView(String context) {


        try {
            CustomMsg customMsg = new Gson().fromJson(context, CustomMsg.class);


            ChatEntity entity = new ChatEntity();
            entity.setSenderName(customMsg.getUserInfo().nickName);
            entity.setContext(customMsg.getActionParam());
            entity.setSex(customMsg.getUserInfo().sex);
            entity.setLevel(customMsg.getUserInfo().level);

            int type = Constants.MEMBER_TEXT_TYPE;
            if(CurLiveInfo.getHostID().equals(customMsg.getUserInfo().userId)){
                type = Constants.HOST_TEXT_TYPE;
            }
            entity.setType(type);


            notifyRefreshListView(entity);

            mListViewMsgItems.setVisibility(View.VISIBLE);
            SxbLog.d(TAG, "refreshTextListView height " + mListViewMsgItems.getHeight());

            if (mListViewMsgItems.getCount() > 1) {
                if (true)
                    mListViewMsgItems.setSelection(0);
                else
                    mListViewMsgItems.setSelection(mListViewMsgItems.getCount() - 1);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    /**
     * 通知刷新消息ListView
     */
    private void notifyRefreshListView(ChatEntity entity) {
        mBoolNeedRefresh = true;
        mTmpChatList.add(entity);
        if (mBoolRefreshLock) {
            return;
        } else {
            doRefreshListView();
        }
    }

    /**
     * 刷新ListView并重置状态
     */
    private void doRefreshListView() {
        if (mBoolNeedRefresh) {
            mBoolRefreshLock = true;
            mBoolNeedRefresh = false;
            mArrayListChatEntity.addAll(mTmpChatList);
            mTmpChatList.clear();
            mChatMsgListAdapter.notifyDataSetChanged();

            if (null != mTimerTask) {
                mTimerTask.cancel();
            }
            mTimerTask = new TimerTask() {
                @Override
                public void run() {
                    SxbLog.v(TAG, "doRefreshListView->task enter with need:" + mBoolNeedRefresh);
                    mHandler.sendEmptyMessage(REFRESH_LISTVIEW);
                }
            };
            //mTimer.cancel();
            mTimer.schedule(mTimerTask, MINFRESHINTERVAL);
        } else {
            mBoolRefreshLock = false;
        }
    }


    private class LiveViewImp implements LiveView{
        private boolean bFirstRender = true;
        @Override
        public void showVideoView(boolean isLocal, String id) {
            SxbLog.i(TAG, "showVideoView " + id);

            //渲染本地Camera
            if (isLocal == true) {
                SxbLog.i(TAG, "showVideoView host :" + LoginInfo.getInstance().getUserId());
                QavsdkControl.getInstance().setSelfId(LoginInfo.getInstance().getUserId());
                QavsdkControl.getInstance().setLocalHasVideo(true, LoginInfo.getInstance().getUserId());
                //主播通知用户服务器
                if (CurLiveInfo.getIdStatus() == Constants.HOST) {
                    if (bFirstRender) {
//                        mEnterRoomHelper.notifyServerCreateRoom();
                        AbstractRequestBack abstractRequestBack = new AbstractRequestBack(){
                            @Override
                            public boolean onResponse(SimpleInfoData response, int id) {
                                if(response.result == 0) {
                                    String live_id = response.data.getAsJsonObject().get("live_id").getAsString();
                                    Log.e("live_id", live_id);
                                    CurLiveInfo.setLiveId(live_id);
                                }
                                return false;
                            }
                        };
                        NetTaskList.getInstance().createLive(context,99,abstractRequestBack);

                        bFirstRender = false;
                    }
                }
            } else {
//            QavsdkControl.getInstance().addRemoteVideoMembers(id);
                Log.e("setRemoteHasVideo","==========================showVideoView");
                QavsdkControl.getInstance().setRemoteHasVideo(true, id, AVView.VIDEO_SRC_TYPE_CAMERA);
            }

        }

        @Override
        public void acceptInvite(String id) {
            memberAcceptInvite(id);
        }

        @Override
        public void showInviteDialog() {
            if ((invitedDialog != null) && (getBaseContext() != null) && (invitedDialog.isShowing() != true)) {
                invitedDialog.show();
            }
        }

        @Override
        public void hideInviteDialog() {
            if ((invitedDialog != null) && (invitedDialog.isShowing() == true)) {
                invitedDialog.dismiss();
            }
        }

        @Override
        public void refreshText(String text, String name, String flag) {
            if("VisibleGroupMsg".equals(flag)){
                refreshTextListView(text);
                return;
            }

            if (text != null) {
                refreshTextListView(name, text, Constants.TEXT_TYPE);
            }
        }

        @Override
        public void refreshThumbUp() {
            CurLiveInfo.setAdmires(CurLiveInfo.getAdmires() + 1);
//            if (!bCleanMode) {      // 纯净模式下不播放飘星动画
//                mHeartLayout.addFavor();
//            }
//            tvAdmires.setText("" + CurLiveInfo.getAdmires());
        }

        @Override
        public void refreshUI(String id) {
            //当主播选中这个人，而他主动退出时需要恢复到正常状态
            if (CurLiveInfo.getIdStatus() == Constants.HOST)
                if (!backGroundId.equals(CurLiveInfo.getHostID()) && backGroundId.equals(id)) {
//                    backToNormalCtrlView();
                }
        }

        @Override
        public boolean showInviteView(String id) {
            return false;
        }

        @Override
        public void cancelInviteView(String id) {
            //TODO handler 超时邀请
            cancelInviteViewed(id);
        }

        @Override
        public void cancelMemberView(String id) {
            //TODO 主动关闭成员摄像头
        }

        @Override
        public void memberJoin(String id, String name, String jsonText) {
            SxbLog.d(TAG, LogConstants.ACTION_VIEWER_ENTER_ROOM + LogConstants.DIV + LoginInfo.getInstance().getUserId() + LogConstants.DIV + "on member join" +
                    LogConstants.DIV + "join room " + id);
            refreshTextListView(TextUtils.isEmpty(name) ? id : name, "来了", Constants.MEMBER_ENTER);

            CurLiveInfo.setMembers(CurLiveInfo.getMembers() + 1);
            count_tv.setText(CurLiveInfo.getMembers() +"人");

            CustomMsg.CustomUserInfo userInfo = new Gson().fromJson(jsonText, CustomMsg.CustomUserInfo.class);
            memberList.add(userInfo);
            memberAdpter.notifyDataSetChanged();
        }

        @Override
        public void memberQuit(String id, String name, String jsonText) {
            refreshTextListView(TextUtils.isEmpty(name) ? id : name, "离开了直播间", Constants.MEMBER_EXIT);

            if (CurLiveInfo.getMembers() > 0) {
                CurLiveInfo.setMembers(CurLiveInfo.getMembers() - 1);
                count_tv.setText(CurLiveInfo.getMembers() + "人");
            }

            CustomMsg.CustomUserInfo userInfo = new Gson().fromJson(jsonText, CustomMsg.CustomUserInfo.class);

            for (CustomMsg.CustomUserInfo userInfoItem: memberList) {
                if(userInfoItem.userId.equals(userInfo.userId)){
                    memberList.remove(userInfoItem);
                    break;
                }
            }
            memberAdpter.notifyDataSetChanged();
            //如果存在视频互动，取消
            QavsdkControl.getInstance().closeMemberView(id);
        }

        @Override
        public void readyToQuit() {
            mEnterRoomHelper.quiteLive();
        }

        @Override
        public void pushStreamSucc(TIMAvManager.StreamRes streamRes) {

        }

        @Override
        public void stopStreamSucc() {

        }

        @Override

        public void startRecordCallback(boolean isSucc) {

        }

        @Override
        public void stopRecordCallback(boolean isSucc, List<String> files) {
            readyToQuit();
            if(isSucc &&  files.size()>0){
                HashMap<String, String> params = new HashMap<>();
                params.put("create_time",System.currentTimeMillis()/1000 + "");
                params.put("vid",files.get(0));
                params.put("watch_count",memberList.size()+"");
                params.putAll(AppInfo.getHeadInfo());
                NetTaskList.addRecord(params);
            }

        }

        @Override
        public void hostLeave(String id, String name) {
            refreshTextListView(TextUtils.isEmpty(name) ? id : name, "离开一会儿!", Constants.HOST_LEAVE);
        }

        @Override
        public void hostBack(String id, String name) {
            refreshTextListView(TextUtils.isEmpty(name) ? id : name, "回来了!", Constants.HOST_BACK);

        }

        @Override
        public void onReceiveGift(String giftId,String senderId) {

            giftShowManager.addGift(giftId, senderId);
        }

        @Override
        public void onReceiveRedPacket(String redPacketId) {
            showRedPacket(redPacketId);
        }
    }

    private UMShareListener umShareListener = new UMShareListener() {
        @Override
        public void onResult(SHARE_MEDIA platform) {
            com.umeng.socialize.utils.Log.d("plat","platform"+platform);
            if(platform.name().equals("WEIXIN_FAVORITE")){
                Toast.makeText(context,platform + " 收藏成功啦",Toast.LENGTH_SHORT).show();
            }else{
                Toast.makeText(context, platform + " 分享成功啦", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void onError(SHARE_MEDIA platform, Throwable t) {
            Toast.makeText(context,platform + " 分享失败啦", Toast.LENGTH_SHORT).show();
            if(t!=null){
                com.umeng.socialize.utils.Log.d("throw","throw:"+t.getMessage());
            }
        }

        @Override
        public void onCancel(SHARE_MEDIA platform) {
            Toast.makeText(context,platform + " 分享取消了", Toast.LENGTH_SHORT).show();
        }
    };
   private void checkPermission() {
        final List<String> permissionsList = new ArrayList<String>();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if ((checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.CAMERA);
            if ((checkSelfPermission(Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.RECORD_AUDIO);
            if ((checkSelfPermission(Manifest.permission.WAKE_LOCK) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.WAKE_LOCK);
            if ((checkSelfPermission(Manifest.permission.MODIFY_AUDIO_SETTINGS) != PackageManager.PERMISSION_GRANTED))
                permissionsList.add(Manifest.permission.MODIFY_AUDIO_SETTINGS);
            if (permissionsList.size() != 0) {
                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]), 0);
            }
        }
    }
}
